﻿using ReflectionStudio.Core.Events;
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using WPFExcelReport.Helpers;
namespace WPFExcelReport
{
    public partial class TEXART
    {
        DataTable TBResult;
        public TEXART()
        {
            if (DesignerProperties.GetIsInDesignMode(this))
                return;
            MV = new VICC_EXART();
            this.DataContext = MV;
            InitializeComponent();
            EventDispatcher.Instance.OnMessage += Instance_OnMessage;
            ART = @"C:\IntexReport\Data\AFSEXAPP\EXCEL";
            VAR = "ITXEX";
        }


        private void Instance_OnMessage(object sender, MessageEventArgs e)
        {
            string msg = e.Info.Details;
            if (msg.Contains("loaded"))
                TMV.INFO = e.Info.Details + Environment.NewLine;
            else
                TMV.VAR = e.Info.Details + Environment.NewLine;
        }

        private void cmdFilterART_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string filter = "ARTICLE LIKE '%" + txtLART.Text.ToString().Trim() + "%'";
                cvMaster.CustomFilter = filter;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace, ex.Message);
            }
        }

        private void btnArtClear_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                cvMaster.CustomFilter = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace, ex.Message);
            }
        }

        public override void QueryCommand(object sender, RoutedEventArgs e)
        {
            try
            {
                TMV.sql = "SELECT DISTINCT ARTICLE,DESCRIPTION,COMPOSITION,WEIGHT,WIDTH,CODE,BOOK,LOCATION,PRICE,SUPPLIER,REMARK FROM ICC_EXART M WHERE  ARTICLE LIKE '" + txtLART.Text.ToString().Trim() + "%'";
                TBResult = TMV.SQLiteDatabase.GetDataTable(TMV.sql);
                TBResult.TableName = "ICC_EXART";
                DataSet Set = new DataSet();
                Set.Merge(TBResult);
                MergeData(Set, false);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
                try
                {
                    TBMain.Clear();
                    TBMain.Merge(TBResult);
                }
                catch (Exception exx)
                { }
            }
        }
        public override void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            IsBusy = false;
            string sql = "UPDATE  ICC_MAXORD SET RATE1=" + TMV.date;
            TMV.SQLiteDatabase.ExecuteNonQuery(sql);
            base.bgWorker_RunWorkerCompleted(sender, e);
        }
        public override void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            DoConvert();
            base.bgWorker_DoWork(sender, e);
        }

        public DataSet PageLoad(DataRow dwData)
        {
            DataSet Set = new DataSet();
            int idx = 0;
            int rows = 100;
            while (true)
            {
                SResult = TMV.VA.QVA06AFSEX(dwData, idx, rows);
                if (SResult.Tables[0].Rows.Count == 0)
                    break;
                SendQ.Enqueue(SResult.Tables[0].Copy());
                AutoRun();
                Set.Merge(SResult);
                idx++;
                EventDispatcher.Instance.RaiseStatus(idx * 100 + " loaded.", StatusEventType.StopProgress);
            }
            return Set;

        }
        
        bool IsRun = false;
        Queue<object> SendQ = new Queue<object>();
        public void AutoRun()
        {
            try
            {
                if (IsRun)
                    return;
                ThreadStart Work = null;
                Thread Thread = null;
                Work = new ThreadStart(DoWriteWork);
                Thread = new Thread(Work);
                Thread.Priority = ThreadPriority.BelowNormal;
                Thread.Start();
            }
            catch (Exception ex)
            {
                // EventDispatcher.Instance.RaiseStatus("发送异常终止", StatusEventType.StopProgress);
                Helpers.LogHelper.error(ex.Message);
            }
        }
        void DoWriteWork()
        {
            ///若是首个任务，则启动运行，初始化端口为空闲
            IsRun = true;
            while (true)
            {
                try
                {
                    if (SendQ.Count == 0)
                    {
                        IsRun = false;
                        break;
                    }
                    Convert2LocalDB((DataTable)SendQ.Dequeue());
                }
                catch (Exception ex)
                {
                    IsRun = false;
                    Helpers.LogHelper.error(ex.Message);
                }

            }
        }
        public void DoConvert()
        {
            TMV.CALL = 0;
            TMV.CNOW = 0;
            string lastdte = "0";
            string sql = "SELECT * FROM ICC_MAXORD";
            TBResult = TMV.SQLiteDatabase.GetDataTable(sql);
            foreach (DataRow row in TBResult.Rows)
            {
                lastdte = row["RATE1"].ToString();
            }
            dwData = TMV.VA.TBMain.NewRow();
            dwData["VAAMANDANT"] = app.Mandant;
            dwData["VAAKOLL"] = "";
            dwData["VAAARTST"] = "F";
            dwData["VAAART"] = "";
            dwData["VAABEZ"] = "";
            dwData["VAADART"] = "";
            dwData["VAAEXCL"] = "";
            dwData["VAAFILLER"] = "";
            dwData["VAAREFART"] = "";
            dwData["VAAARTFAM"] = "";
            dwData["VAAARTFIN"] = " AND VAAAENDDAT>=" + lastdte;
            //dwData["VAAARTFIN"] = " AND ROWNUM<100";
            //供应商 
            SResult = PageLoad(dwData);

            if (SResult.Tables.Count > 0)
            {
                SResult.Tables[0].TableName = "ICC_EXART";
                //Convert2LocalDB(SResult.Tables[0]);
                //MergeData(SResult, false);
            } 
        }
        private void btnResetDB_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                IsBusy = true;
                bgWorker.RunWorkerAsync();

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void Convert2LocalDB(DataTable tbArt)
        {
            try
            {
                string sql = "";
                //sql = "DELETE FROM ICC_EXORD";
                //SQLiteDatabase.ExecuteNonQuery(sql);
                sql = "insert into ICC_EXART(ARTICLE,DESCRIPTION,COMPOSITION,WEIGHT,WIDTH,CODE,BOOK,LOCATION,PRICE,SUPPLIER,REMARK) values ";
                string values = "";
                int idx = 1;
                int ids = -1;
                int smallidx = 0;
                int count = tbArt.Rows.Count;

                foreach (DataRow row in tbArt.Rows)
                {
                    TMV.SQLiteDatabase.ExecuteNonQuery("DELETE FROM ICC_EXART WHERE RTRIM(ARTICLE)='" + row["ARTICLE"].ToString().Replace("'", "''") + "'");
                    EventDispatcher.Instance.RaiseStatus(TMV.CNOW + " is converting.", StatusEventType.RunningProgress);
                    values += "(";
                    values += "'" + row["ARTICLE"].ToString().Replace("'", "''") + "',";
                    values += "'" + row["DESCRIPTION"].ToString().Replace("'", "''") + "',";
                    values += "'" + row["COMPOSITION"].ToString().Replace("'", "''") + "',";
                    values += "'" + row["WEIGHT"].ToString().Replace("'", "''") + "',";
                    values += "'" + row["WIDTH"].ToString() + "',";
                    values += "'" + row["CODE"].ToString() + "',";
                    values += "'" + row["BOOK"].ToString() + "',";
                    values += "'" + row["LOCATION"].ToString() + "',";
                    values += "'" + row["PRICE"].ToString().Replace("'", "''") + "',";
                    values += "'" + row["LSLIEFNA"].ToString().Replace("'", "''") + "',";
                    values += "'" + row["REMARK"].ToString().Replace("'", "''") + "'),";

                   TMV.CNOW++;
                    idx++;
                    smallidx++;
                    if (smallidx > 100)
                    {
                        smallidx = 0;
                        values += "***";
                        values = values.Replace(",***", ";");
                        sql += values;
                        TMV.SQLiteDatabase.ExecuteNonQuery(sql);
                        sql = "insert into ICC_EXART(ARTICLE,DESCRIPTION,COMPOSITION,WEIGHT,WIDTH,CODE,BOOK,LOCATION,PRICE,SUPPLIER,REMARK) values ";
                        values = "";
                    }
                }
                values += "***";
                values = values.Replace(",***", ";");
                sql += values;
                TMV.SQLiteDatabase.ExecuteNonQuery(sql);
                EventDispatcher.Instance.RaiseStatus(TMV.CNOW + " converted.", StatusEventType.StopProgress);
            }

            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void LoadExcelCommand(object sender, RoutedEventArgs e)
        {
            cDR.PRINT(null);
            if (cDR.SetExchange == null)
                return;
            if (cDR.SetExchange.Tables.Count == 0)
                return;
            foreach (DataRow row in cDR.SetExchange.Tables[0].Rows)
            {
                foreach (DataColumn c in cDR.SetExchange.Tables[0].Columns)
                {
                    row[c] = Helper.ConvertGB2312To8859P1(row[c].ToString());
                }
            }
            Convert2LocalDB(cDR.SetExchange.Tables[0]);
            MergeData(cDR.SetExchange, true, true);
        }
    }
}